import { Component, OnInit, Host } from "@angular/core";
import { SpotlightsService } from "../spotlights.service";
import { AppComponent } from "../../../../app.component";
import { ActivatedRoute, Router } from "@angular/router";
import { SpotlightModel, SpotlightCategory, SpotlightRegion, SpotlightAvailability, SpotlightStatus } from "../model/spotlights.model";
import * as moment from 'moment';
import { ToasterService } from "angular2-toaster";

@Component({
    templateUrl: './spotlight.component.html',
    providers: [SpotlightsService]
})
export class SpotlightComponent implements OnInit {
    public spotlight: SpotlightModel;
    public edit: string = 'false';
    public categories: typeof SpotlightCategory = SpotlightCategory;
    public regions: typeof SpotlightRegion = SpotlightRegion;
    public availability: typeof SpotlightAvailability = SpotlightAvailability;
    public canEdit: boolean = false;
    public quillOptions: any = {
        toolbar: [
            ['bold', 'italic', 'underline', 'strike'],        // toggled buttons            
            [{ 'size': ['small', false, 'large', 'huge'] }],  // custom dropdown
            [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
            ['link']                         // link and image, video
        ]
    }

    constructor(@Host() private rootComponent: AppComponent,
        private spotlightsService: SpotlightsService,
        private route: ActivatedRoute,
        private router: Router,
        private toasterService: ToasterService
    ) { }

    ngOnInit(): void {
        this.route.params.subscribe(param => {
            this.edit = param['edit'];
            if (this.edit == 'true') {
                this.spotlightsService.getSpotlight(param['id']).subscribe(data => {
                    this.spotlight = this.loadData(data);
                    this.canEdit = this.spotlight.status == SpotlightStatus.Draft;
                });
            }
            else {
                this.spotlight = new SpotlightModel();
                this.spotlight.availableFor = this.availability.All;
                this.canEdit = true;
            }
        });

        this.rootComponent.finishLoading();
    }

    public changeAvailability(newAvailability: SpotlightAvailability) {
        if (this.spotlight.availableFor != newAvailability)
            this.spotlight.availableFor = newAvailability;
    }

    public publishSpotlight() {
        if (this.validSpotlight()) {
            this.saveData(moment(this.spotlight.dateCreated) < moment() && moment() < moment(this.spotlight.unpublishedDate) ? SpotlightStatus.Published : SpotlightStatus.Unpublished);
        }
    }

    public saveSpotlight() {
        if (this.validSpotlight()) {
            this.saveData(SpotlightStatus.Draft);
        }
    }

    private goBack() {
        this.router.navigate(['../../'], { relativeTo: this.route });
    }

    private validSpotlight(): boolean {
        let ret: boolean = true;
        if (!this.spotlight.title) {
            this.toasterService.pop('warning', 'Warning', 'Article title required.');
            ret = false;
        }

        if (this.spotlight.dateCreated && this.spotlight.unpublishedDate) {
            if (moment(this.spotlight.dateCreated) > moment(this.spotlight.unpublishedDate)) {
                this.toasterService.pop('warning', 'Warning', 'Unpublish date must be after publish date.');
                ret = false;
            }
        }
        else {
            if (!this.spotlight.dateCreated) {
                this.toasterService.pop('warning', 'Warning', 'Date required');
                ret = false;
            }
            if (!this.spotlight.unpublishedDate) {
                this.toasterService.pop('warning', 'Warning', 'Unpublish date required');
                ret = false;
            }
        }

        if (!this.spotlight.body) {
            this.toasterService.pop('warning', 'Warning', 'News content required');
            ret = false;
        }

        return ret;
    }

    private loadData(spotlight: SpotlightModel): SpotlightModel {
        if (spotlight.tags)
            spotlight.tags = spotlight.tags.map(function (o) { return { display: o.name, value: o.name } });
        if (spotlight.dateCreated)
            spotlight.dateCreated = new Date(spotlight.dateCreated);
        if (spotlight.unpublishedDate)
            spotlight.unpublishedDate = new Date(spotlight.unpublishedDate);
        return spotlight;
    }

    private saveData(status: SpotlightStatus) {
        if (this.spotlight.tags)
            this.spotlight.tags = this.spotlight.tags.map(function (o) { return { name: o.value } });

        this.spotlight.status = status;
        if (this.canEdit && this.edit == 'true')
            this.spotlightsService.saveSpotlight(this.spotlight).subscribe(_ => this.goBack());
        else
            this.spotlightsService.publishSpotlight(this.spotlight).subscribe(_ => this.goBack());
    }
}